package edu.uoc.tds.pec4.vista;

import edu.uoc.tds.pec4.gestor.GestorInformes;
import edu.uoc.tds.pec4.model.SS1_CentroDocente;
import edu.uoc.tds.pec4.model.SS1_Universidad;
import edu.uoc.tds.pec4.model.SS2_Evento;
import edu.uoc.tds.pec4.model.SS3_InformeEventosAsistente;
import edu.uoc.tds.pec4.util.ComponentsUtils;
import edu.uoc.tds.pec4.util.ExceptionUtils;
import edu.uoc.tds.pec4.util.KeyValue;
import edu.uoc.tds.pec4.util.LanguageUtils;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 * Tecnicas de Desarrollo de Software - (UOC)
 * Clase que modela la pantalla de Informe de Asistencia a un Evento
 * @author José Carlos Fernández Luque
 * @version 1.0
 */
public class SS3_PantallaAsistenciaEvento extends javax.swing.JPanel {

    /**
     *
     */
    public float sumaImport;
    /**
     *
     */
    public GestorInformes objetoRemoto;
    private boolean isInitialCharge = false;

    /**
     * 
     * @param objetoRemoto
     */
    public SS3_PantallaAsistenciaEvento(GestorInformes objetoRemoto) {
        this.objetoRemoto = objetoRemoto;
        initComponents();
        formatLanguage();
        intialCharge();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        resultPanel = new javax.swing.JPanel();
        resultScroll = new javax.swing.JScrollPane();
        resultTable = new javax.swing.JTable();
        searchPanel = new javax.swing.JPanel();
        eventLabel = new javax.swing.JLabel();
        eventCombo = new javax.swing.JComboBox();
        centerLabel = new javax.swing.JLabel();
        universityLabel = new javax.swing.JLabel();
        cleanButton = new javax.swing.JButton();
        findButton = new javax.swing.JButton();
        assistantLabel = new javax.swing.JLabel();
        universityCombo = new javax.swing.JComboBox();
        centerCombo = new javax.swing.JComboBox();
        assistantCombo = new javax.swing.JComboBox();
        tittleLabel = new javax.swing.JLabel();

        resultPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultado de la búsqueda"));

        resultTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Nombre", "Apellido1", "Apellido 2", "Rol", "DNI", "Centro", "Asistencia"
            }
        ));
        resultScroll.setViewportView(resultTable);

        javax.swing.GroupLayout resultPanelLayout = new javax.swing.GroupLayout(resultPanel);
        resultPanel.setLayout(resultPanelLayout);
        resultPanelLayout.setHorizontalGroup(
            resultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(resultPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(resultScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 612, Short.MAX_VALUE)
                .addContainerGap())
        );
        resultPanelLayout.setVerticalGroup(
            resultPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(resultPanelLayout.createSequentialGroup()
                .addComponent(resultScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                .addContainerGap())
        );

        searchPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Criterios de búsqueda"));

        eventLabel.setText("Eventos");

        eventCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        centerLabel.setText("Centro");

        universityLabel.setText("Univesidad");

        cleanButton.setText("Limpiar");
        cleanButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cleanButtonActionPerformed(evt);
            }
        });

        findButton.setText("Buscar");
        findButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                findButtonActionPerformed(evt);
            }
        });

        assistantLabel.setText("Asistencia");

        universityCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        universityCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                universityComboItemStateChanged(evt);
            }
        });

        centerCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        assistantCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(universityLabel)
                    .addComponent(centerLabel)
                    .addComponent(eventLabel))
                .addGap(25, 25, 25)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(eventCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addComponent(centerCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(32, 32, 32)
                        .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, searchPanelLayout.createSequentialGroup()
                                .addComponent(cleanButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(findButton, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(searchPanelLayout.createSequentialGroup()
                                .addGap(168, 168, 168)
                                .addComponent(assistantLabel)
                                .addGap(18, 18, 18)
                                .addComponent(assistantCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(universityCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(65, Short.MAX_VALUE))
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(universityLabel)
                    .addComponent(universityCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(assistantLabel)
                    .addComponent(assistantCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(centerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(centerCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(eventLabel)
                            .addComponent(eventCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(searchPanelLayout.createSequentialGroup()
                        .addGap(58, 58, 58)
                        .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(findButton)
                            .addComponent(cleanButton))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tittleLabel.setFont(new java.awt.Font("Tahoma", 1, 14));
        tittleLabel.setText("Informe de Asisatentes a un Evento");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(188, 188, 188)
                .addComponent(tittleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(searchPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(resultPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(tittleLabel)
                .addGap(11, 11, 11)
                .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resultPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void findButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findButtonActionPerformed
        cercaResult();
    }//GEN-LAST:event_findButtonActionPerformed

    private void cleanButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cleanButtonActionPerformed
        universityCombo.setSelectedIndex(0);
        centerCombo.setSelectedIndex(0);
        eventCombo.setSelectedIndex(0);
        assistantCombo.setSelectedIndex(0);
    }//GEN-LAST:event_cleanButtonActionPerformed

    private void universityComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_universityComboItemStateChanged
        if (!isInitialCharge) {
            cargaComboCentrosPorUniversidad(centerCombo);
        }
    }//GEN-LAST:event_universityComboItemStateChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox assistantCombo;
    private javax.swing.JLabel assistantLabel;
    private javax.swing.JComboBox centerCombo;
    private javax.swing.JLabel centerLabel;
    private javax.swing.JButton cleanButton;
    private javax.swing.JComboBox eventCombo;
    private javax.swing.JLabel eventLabel;
    private javax.swing.JButton findButton;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel resultPanel;
    private javax.swing.JScrollPane resultScroll;
    private javax.swing.JTable resultTable;
    private javax.swing.JPanel searchPanel;
    private javax.swing.JLabel tittleLabel;
    private javax.swing.JComboBox universityCombo;
    private javax.swing.JLabel universityLabel;
    // End of variables declaration//GEN-END:variables

    private void formatLanguage() {
        assistantLabel.setText(LanguageUtils.getMessage("SS3.asistente"));
        centerLabel.setText(LanguageUtils.getMessage("SS3.centro"));
        universityLabel.setText(LanguageUtils.getMessage("SS3.universidad"));
        findButton.setText(LanguageUtils.getMessage("SS3.buscar"));
        cleanButton.setText(LanguageUtils.getMessage("SS3.limpiar"));
        tittleLabel.setText(LanguageUtils.getMessage("SS3.InformeAsistenteEvento"));
        eventLabel.setText(LanguageUtils.getMessage("SS3.evento"));
        searchPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(LanguageUtils.getMessage("SS3.criterioBusqueda")));
        resultPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(LanguageUtils.getMessage("SS3.resultadoBusqueda")));
    }

    private void intialCharge() {
        isInitialCharge = true;
        cargaCombo(universityCombo, "universidades");
        cargaCombo(centerCombo, "centros");
        cargaCombo(eventCombo, "eventos");
        cargaCombo(assistantCombo, "asistencia");
        List listCostByEvent = new ArrayList();
        resultTable = carregaResutTable(resultTable, listCostByEvent);
        isInitialCharge = false;
    }

    private void cargaComboCentrosPorUniversidad(JComboBox centerComb) {
        try {
            List lista = new ArrayList();
            lista = objetoRemoto.dameCentrosUniversidad((SS1_Universidad) universityCombo.getSelectedItem());
            SS1_CentroDocente nullElement = new SS1_CentroDocente();
            nullElement.setId(-1);
            lista.add(0, nullElement);
            ComponentsUtils.cargaCombo(centerComb, lista);
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("ERR_Remote"));
            Logger.getLogger(SS3_PantallaAsistenciaEvento.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Inesperado);
            Logger.getLogger(SS3_PantallaAsistenciaEvento.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cargaCombo(JComboBox combo, String string) {
        List lista = new ArrayList();
        try {
            if (string.equalsIgnoreCase("universidades")) {
                lista = objetoRemoto.getComboUniversidades();
                SS1_Universidad nullElement = new SS1_Universidad();
                nullElement.setId(-1);
                lista.add(0, nullElement);
            } else if (string.equalsIgnoreCase("centros")) {
                lista = objetoRemoto.getComboCentroDocente();
                SS1_CentroDocente nullElement = new SS1_CentroDocente();
                nullElement.setId(-1);
                lista.add(0, nullElement);
            } else if (string.equalsIgnoreCase("eventos")) {
                lista = objetoRemoto.getComboEventos();
                SS2_Evento eventNull = new SS2_Evento();
                eventNull.setidEvento(-1);
                lista.add(0, eventNull);
            } else if (string.equalsIgnoreCase("asistencia")) {
                lista.add(new KeyValue(null, ""));
                lista.add(new KeyValue(0, "Asistentes"));
                lista.add(new KeyValue(1, "No Asistentes"));
            }
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Inesperado);
            Logger.getLogger(SS3_PantallaAsistenciaEvento.class.getName()).log(Level.SEVERE, null, ex);
        }
        ComponentsUtils.cargaCombo(combo, lista);
    }

    private JTable carregaResutTable(JTable table, List list) {
        table.removeAll();
        ModelResult model = new ModelResult(list);
        table.setModel(model);
        return table;
    }

    private void cercaResult() {
        List<SS3_InformeEventosAsistente> list = null;
        try {
            list = (ArrayList<SS3_InformeEventosAsistente>) objetoRemoto.dameResultAsistentesEvento(
                    (SS1_Universidad) universityCombo.getSelectedItem(),
                    (SS1_CentroDocente) centerCombo.getSelectedItem(),
                    (SS2_Evento) eventCombo.getSelectedItem(), (KeyValue) assistantCombo.getSelectedItem());
        } catch (RemoteException ex) {
            ExceptionUtils.visualizarError(LanguageUtils.getMessage("ERR_Remote"));
            Logger.getLogger(SS3_PantallaAsistenciaEvento.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            ExceptionUtils.visualizarError(ExceptionUtils.ERR_Inesperado);
            Logger.getLogger(SS3_PantallaAsistenciaEvento.class.getName()).log(Level.SEVERE, null, ex);
        }
        resultTable = carregaResutTable(resultTable, list);
    }

    class ModelResult extends AbstractTableModel {

        private static final long serialVersionUID = 1L;
        protected Vector<String> cabecera = new Vector<String>();
        protected Vector<Vector> eventosAsistente = new Vector<Vector>();

        public ModelResult(List<SS3_InformeEventosAsistente> lissS3_InformeEventosAsistente) {
            setCapcelera();
            setResulTabla(lissS3_InformeEventosAsistente);
        }

        private void setCapcelera() {
            cabecera.add(LanguageUtils.getMessage("SS3.nombre"));
            cabecera.add(LanguageUtils.getMessage("SS3.apellido1"));
            cabecera.add(LanguageUtils.getMessage("SS3.apellido2"));
            cabecera.add(LanguageUtils.getMessage("SS3.rol"));
            cabecera.add(LanguageUtils.getMessage("SS3.numDocumento"));
            cabecera.add(LanguageUtils.getMessage("SS3.centro"));
            cabecera.add(LanguageUtils.getMessage("SS3.asistencia"));
        }

        private void setResulTabla(List<SS3_InformeEventosAsistente> listSS3_InformeEventosAsistente) {
            Vector<String> nameColumn = new Vector<String>();
            Vector<String> surName1Column = new Vector<String>();
            Vector<String> surName2Column = new Vector<String>();
            Vector<String> rolColumn = new Vector<String>();
            Vector<String> numDocColumn = new Vector<String>();
            Vector<String> centerColumn = new Vector<String>();
            Vector<String> assistantColumn = new Vector<String>();

            for (Iterator<SS3_InformeEventosAsistente> it = listSS3_InformeEventosAsistente.iterator(); it.hasNext();) {
                SS3_InformeEventosAsistente sS3_InformeEventosAsistente = it.next();
                nameColumn.add(sS3_InformeEventosAsistente.getNombreUsuario());
                surName1Column.add(sS3_InformeEventosAsistente.getApellido1());
                surName2Column.add(sS3_InformeEventosAsistente.getApellido2());
                rolColumn.add(sS3_InformeEventosAsistente.getRol() == 0
                        ? LanguageUtils.getMessage("SS3.estudiante")
                        : sS3_InformeEventosAsistente.getRol() == 1
                        ? LanguageUtils.getMessage("SS3.profesor") : LanguageUtils.getMessage("SS3.otros"));
                numDocColumn.add(sS3_InformeEventosAsistente.getdNI());
                centerColumn.add(sS3_InformeEventosAsistente.getCentro());
                assistantColumn.add(sS3_InformeEventosAsistente.getEstadoAsistente() == true ? LanguageUtils.getMessage("SS3.si") : LanguageUtils.getMessage("SS3.no"));
            }
            eventosAsistente.add(nameColumn);
            eventosAsistente.add(surName1Column);
            eventosAsistente.add(surName2Column);
            eventosAsistente.add(rolColumn);
            eventosAsistente.add(numDocColumn);
            eventosAsistente.add(centerColumn);
            eventosAsistente.add(assistantColumn);
        }

        public int getRowCount() {
            return (((Vector) eventosAsistente.get(0)).size());
        }

        public int getColumnCount() {
            return (eventosAsistente.size());
        }

        @Override
        public String getColumnName(int col) {
            return ((String) cabecera.get(col));
        }

        public boolean getScrollableTrackViewportHeight() {
            return (true);
        }

        public boolean getScrollableTrackViewportWidth() {
            return (true);
        }

        public Object getValueAt(int fila, int col) {
            return (((Vector) eventosAsistente.get(col)).get(fila));
        }

        @Override
        public boolean isCellEditable(int fila, int columna) {
            return (false);
        }
    }
}
